//
//  PlayerSearchViewController.m
//  SportsApp
//
//  Created by Matthew Moritz on 2012-12-05.
//  Copyright (c) 2012 Matthew Moritz. All rights reserved.
//

#import "PlayerSearchViewController.h"
#import "PlayerTableViewCell.h"
#import "JsonData.h"

@interface PlayerSearchViewController ()

@end

@implementation PlayerSearchViewController

@synthesize searchTextBox;
@synthesize playerName;
@synthesize playerPhoto;

@synthesize playerStatTable;
@synthesize playerInfoTable;
@synthesize playerEntries;

@synthesize totalAssists;
@synthesize totalGoals;
@synthesize totalPims;
@synthesize totalPoints;

@synthesize currentSeason;
@synthesize seasonLabel;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    currentSeason = @"2011";
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)nameEntered:(id)sender {
}

- (IBAction)updatePressed:(id)sender {
    
    playerName = searchTextBox.text;
    
    /* Set the season label */
    int startYear = [currentSeason intValue];
    int endYear   = [currentSeason intValue] + 1;
    
    seasonLabel.text = [NSString stringWithFormat:@"%d - %d", startYear, endYear];
    
    NSString *queryPlayerName = [playerName stringByReplacingOccurrencesOfString:@" " withString:@"+"];
    
    //build query and execute
    JsonData *data = [[JsonData alloc]init];
    
    NSURL *url = [data buildPlayerURL:queryPlayerName:currentSeason];   // build URL
    playerEntries = [data executeQuery:url]; // execute query
    
    // Checks if the player name is valid
    if (playerEntries.count < 2) {
        NSLog(@"ERROR: Player %@ did not return anything.", playerName);
        
        // show an alert, and abort
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Error" message:[NSString stringWithFormat:@"There were no results for %@", playerName] delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil];
        
        [alert show];
    }
    
    else {
        [playerInfoTable reloadData];
        [playerStatTable reloadData];
        [self calculateSeasonTotals:playerEntries];
    }
}

/**
 * Calculates the season totals of the selected player
 *
 */
-(void)calculateSeasonTotals:entries {
    
    int points = 0;
    int goals = 0;
    int assists = 0;
    int pims = 0;
    
    NSString *p, *g, *a, *ps;
    
    for(int i=0; i < [entries[@"date"] count]; i++) {
        
        p = [NSString stringWithFormat:@"%@",[NSString stringWithFormat: @"%@", [playerEntries[[NSString stringWithFormat:@"%@:points", playerName]] objectAtIndex:i]]];
        
        g = [NSString stringWithFormat:@"%@",[NSString stringWithFormat: @"%@", [playerEntries[[NSString stringWithFormat:@"%@:goals", playerName]] objectAtIndex:i]]];
        
        a = [NSString stringWithFormat:@"%@",[NSString stringWithFormat: @"%@", [playerEntries[[NSString stringWithFormat:@"%@:assists", playerName]] objectAtIndex:i]]];
        
        ps = [NSString stringWithFormat:@"%@",[NSString stringWithFormat: @"%@", [playerEntries[[NSString stringWithFormat:@"%@:penalty minutes", playerName]] objectAtIndex:i]]];
        
        /* points */
        if ([p rangeOfString:@"null"].location == NSNotFound)
            points += [p intValue];
        /* goals */
        if ([g rangeOfString:@"null"].location == NSNotFound)
            goals += [g intValue];
        /* assists */
        if ([a rangeOfString:@"null"].location == NSNotFound)
            assists += [a intValue];
        /* pims */
        if ([ps rangeOfString:@"null"].location == NSNotFound)
            pims += [ps intValue];
    }
    
    /* set the labels */
    totalPoints.text = [NSString stringWithFormat:@"%d", points];
    totalGoals.text = [NSString stringWithFormat:@"%d", goals];
    totalAssists.text = [NSString stringWithFormat:@"%d", assists];
    totalPims.text = [NSString stringWithFormat:@"%d", pims];
}

-(void)updateAll:(NSString *) name {
    
}

#pragma mark UITableViewDataSource


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if(tableView == playerInfoTable) {
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PlayerInfoCell"];
        
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"PlayerInfoCell"];
        }
        
        int row = indexPath.row;
        
        @try {
            
            if(row == 0) {
                cell.textLabel.text = @"Player Name";
                
                if(playerName != nil)
                    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@", playerName];
                else
                    cell.detailTextLabel.text = [NSString stringWithFormat:@""];
            }
            else if(row == 1) {
                cell.textLabel.text = @"Player Number";
                
                if(playerName != nil)
                    cell.detailTextLabel.text = [NSString stringWithFormat: @"%@", [playerEntries[[NSString stringWithFormat:@"%@:number", playerName]] objectAtIndex:0]];
                else
                    cell.detailTextLabel.text = [NSString stringWithFormat:@""];
            }
            else {
                cell.textLabel.text = @"Position";
                
                if(playerName != nil)
                    cell.detailTextLabel.text = [NSString stringWithFormat: @"%@", [playerEntries[[NSString stringWithFormat:@"%@:position", playerName]] objectAtIndex:0]];
                else
                    cell.detailTextLabel.text = [NSString stringWithFormat:@""];
            }
        }
        @catch (NSException * e) {
            return NULL;
        }
        
        return cell;
    }

    else if(tableView == playerStatTable) {
        
        PlayerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PlayerStatCell"];
        
        if (cell == nil) {
            cell = [[PlayerTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"PlayerStatCell"];
        }
        
        int row = indexPath.row;
        
        @try {
            
            /*
             * Add date
             */
            NSString *year  = [[[playerEntries[@"date"] objectAtIndex:row] stringValue] substringWithRange:NSMakeRange(0, 4)];
            NSString *month = [[[playerEntries[@"date"] objectAtIndex:row] stringValue] substringWithRange:NSMakeRange(4, 2)];
            NSString *day   = [[[playerEntries[@"date"] objectAtIndex:row] stringValue] substringWithRange:NSMakeRange(6, 2)];
            NSString *date  = [NSString stringWithFormat:@"%@-%@-%@", year, month, day];
            
            if([date isKindOfClass:[NSString class]])
                cell.dateLabel.text = date;
            else
                cell.dateLabel.text = @"Not Available";
            
            /*
             * Add goals
             */
            NSString *goals = [NSString stringWithFormat:@"%@",[NSString stringWithFormat: @"%@", [playerEntries[[NSString stringWithFormat:@"%@:goals", playerName]] objectAtIndex:row]]];
            cell.goalsLabel.text = goals;
            
            /*
             * Add assists
             */
            NSString *assists = [NSString stringWithFormat:@"%@",[NSString stringWithFormat: @"%@", [playerEntries[[NSString stringWithFormat:@"%@:assists", playerName]] objectAtIndex:row]]];
            cell.assistsLabel.text = assists;

            
            /*
             * Add points
             */
            NSString *points = [NSString stringWithFormat:@"%@",[NSString stringWithFormat: @"%@", [playerEntries[[NSString stringWithFormat:@"%@:points", playerName]] objectAtIndex:row]]];
            cell.pointsLabel.text = points;
            
            /*
             * Add pentaly minutes
             */
            NSString *pim = [NSString stringWithFormat:@"%@",[NSString stringWithFormat: @"%@", [playerEntries[[NSString stringWithFormat:@"%@:penalty minutes", playerName]] objectAtIndex:row]]];
            cell.pimLabel.text = pim;
            
            /*
             * Add +/-
             */
            NSString *plusMinus = [NSString stringWithFormat:@"%@",[NSString stringWithFormat: @"%@", [playerEntries[[NSString stringWithFormat:@"%@:plus minus", playerName]] objectAtIndex:row]]];
            cell.plusMinusLabel.text = plusMinus;
            
            /*
             * Add shots on goal
             */
            NSString *shots = [NSString stringWithFormat:@"%@",[NSString stringWithFormat: @"%@", [playerEntries[[NSString stringWithFormat:@"%@:shots on goal", playerName]] objectAtIndex:row]]];
            cell.shotsLabel.text = shots;
            
            /*
             * Add faceoffs
             */
            NSString *faceoffs = [NSString stringWithFormat:@"%@",[NSString stringWithFormat: @"%@", [playerEntries[[NSString stringWithFormat:@"%@:faceoffs won", playerName]] objectAtIndex:row]]];
            cell.faceoffsLabel.text = faceoffs;
            
        }
        @catch (NSException * e) {
            return NULL;
        }
        
        return cell;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return nil;
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if(tableView == playerInfoTable)
        return 3;
    else
        return [playerEntries[@"date"] count];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (IBAction)changeSeason:(UIStepper *)sender {
    
    currentSeason = [NSString stringWithFormat:@"%0.0f",sender.value]; /* Update the season. */
    [self updatePressed:nil];
}

- (IBAction)textFieldDoneEditing:(id)sender {
    [sender resignFirstResponder];
}

- (IBAction)backgroundTap:(id)sender {
    
    [self.view endEditing:YES];
}

@end
